﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace Magic.Core;

public class UnifyResultStatusCodesMiddleware
{
    /// <summary>
    /// 请求委托
    /// </summary>
    private readonly RequestDelegate _next;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="next"></param>
    public UnifyResultStatusCodesMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    /// <summary>
    /// 中间件执行方法
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task InvokeAsync(HttpContext context)
    {
        await _next(context);

        var statusCode = context.Response.StatusCode;
        // 只有请求错误（短路状态码）和非 WebSocket 才支持规范化处理
        if (IsWebSocketRequest(context)
            || statusCode < 400
            || statusCode == 404) return;

        switch (statusCode)
        {
            // 处理 401 状态码
            case StatusCodes.Status401Unauthorized:
                await context.Response.WriteAsJsonAsync(new RestfulResult<object>
                {
                    Code = context.Response.StatusCode,
                    Msg= "401 Unauthorized"
                });
                break;
            // 处理 403 状态码
            case StatusCodes.Status403Forbidden:
                await context.Response.WriteAsJsonAsync(new RestfulResult<object>
                {
                    Code = context.Response.StatusCode,
                    Msg = "403 Forbidden"
                });
                break;

            default: break;
        }




    }

    /// <summary>
    /// 判断是否是 WebSocket 请求
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private bool IsWebSocketRequest(HttpContext context)
    {
        return context.WebSockets.IsWebSocketRequest || context.Request.Path == "/ws";
    }
}
